"""
Initialize SQLite database.

A Python module is a singleton, called only once despite multiple imports. So, the ini‐
tialization code in init.py is run only once, when the first import of it occurs.
"""

import os
from pathlib import Path
from sqlite3 import Connection, Cursor, IntegrityError, connect

DB_FILE = "cryptid.db"

conn: Connection | None = None
curs: Cursor | None = None


def init_db(file_name: str = None, reset: bool = False):
    global conn, curs

    if conn:
        if not reset:
            return
        conn = None

    db_path = None
    if not file_name:
        db_path = os.environ.get("CRYPTID_SQLITE_DB")

    if not db_path:
        top_dir = Path(__file__).resolve().parents[1]  # repo top
        db_path = str(top_dir / DB_FILE)

    conn = connect(db_path, check_same_thread=False)
    curs = conn.cursor()


init_db()
